package com.luo.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;

import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.util.Calendar;
import java.util.Map;

@Component
public class JwtUtil {
    private static final String SIGN = "luoqianyi";
    //生成token
    public static String setToken(Map<String,String> map){
        Calendar instance = Calendar.getInstance();
        //设置3小时过期
        instance.add(Calendar.HOUR,3);

        //创建jwt builder
        JWTCreator.Builder builder = JWT.create();

        map.forEach((k,v)->{
            builder.withClaim(k,v);
        });

        String token = builder.withExpiresAt(instance.getTime()).sign(Algorithm.HMAC256(SIGN));//指定令牌过期时间
        System.out.println("CREATE TOKEN:"+token);

        return "Bearer "+token;
    }
    //验证token
    public static DecodedJWT verify(String token){
        String natural_token = token.replace("Bearer ","");
        return JWT.require(Algorithm.HMAC256(SIGN)).build().verify(natural_token);
    }

    //获取用户名信息
    public static String getUser(String token){
        String natural_token = token.replace("Bearer ","");
        Key key = new SecretKeySpec(SIGN.getBytes(),
                SignatureAlgorithm.HS256.getJcaName());
        Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(natural_token).getBody();
        return (String)claims.get("user");
    }
}
